import time
from django.test import LiveServerTestCase
from selenium import webdriver
import unittest

# 功能测试： 从外部-用户角度测试
# 单元测试： 从内部-程序员角度测试

# Django请求流程
# 1）一个HTTP请求访问特定URL
# 2）Django根据路由规则匹配对应的视图函数来处理该请求
# 3）视图函数处理请求，并返回HTTP响应

# 需要下载chromedriver才能正常执行
# 根据机器Chrome浏览器版本下载对应的chromedriver,拷贝到/usr/local/bin/目录下即可
# https://npm.taobao.org/mirrors/chromedriver/
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.keys import Keys

MAX_WAIT = 10


# class NewVisitorTest(unittest.TestCase):
class FunctionalTest(LiveServerTestCase):

    # setUp和tearDown特殊方法会在每一个测试案例开始之前和结束之后执行
    def setUp(self):
        self.browser = webdriver.Chrome()

    def tearDown(self):
        self.browser.quit()

    def check_for_row_in_list_table(self, row_text):
        # 在列表表格中找刚才输入的内容
        table = self.browser.find_element_by_id('id_list_table')
        # 注意找到的是多个
        rows = table.find_elements_by_tag_name('tr')
        self.assertIn(row_text, [row.text for row in rows])

    def wait_for_row_in_list_table(self, row_text):
        start_time = time.time()
        while True:
            try:
                # 在列表表格中找刚才输入的内容
                table = self.browser.find_element_by_id('id_list_table')
                # 注意找到的是多个
                rows = table.find_elements_by_tag_name('tr')
                self.assertIn(row_text, [row.text for row in rows])
                return
            except (AssertionError, WebDriverException) as e:
                if time.time() - start_time > MAX_WAIT:
                    raise e
                time.sleep(.5)

    def wait_for(self, func):
        start_time = time.time()
        while True:
            try:
                return func()
            except (AssertionError, WebDriverException) as e:
                if time.time() - start_time > MAX_WAIT:
                    raise e
                time.sleep(.5)

    def get_item_input_box(self):
        return self.browser.find_element_by_id('id_text')

